package cn.jee.controller;

import cn.jee.entity.Stu;
import cn.jee.entity.Teacher;
import cn.jee.repository.StuRepository;
import cn.jee.repository.TeacherRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;
import java.util.Optional;


@Controller
@RequestMapping("/assignment")

public class AssignController {
  @Autowired
  TeacherRepository teacherRepository;
  @Autowired
  StuRepository stuRepository;
  @RequestMapping("/page")
  public String showAssignPage(@RequestParam Long teacherId, Model model){
    Teacher teacher = teacherRepository.findById(teacherId).orElse(null);
    // 查询已分配学生列表
    List<Stu> allocated = stuRepository.findByTeacherId(teacherId);

    // 查询未分配的学生
    List<Stu> notAllocated = stuRepository.findByTeacherIsNull();
    // 将数据传递到前端页面
    model.addAttribute("teacher", teacher);
    model.addAttribute("assignedList", allocated);
    model.addAttribute("unassignedList", notAllocated);


    return "assignPage";
  }
  @RequestMapping("/assignStudent")
  public String doAssign(@RequestParam Long teacherId, @RequestParam Long studentId) {
    Optional<Stu> optionalStu = stuRepository.findById(studentId);
    Optional<Teacher> optionalTeacher = teacherRepository.findById(teacherId);

    if (optionalStu.isPresent() && optionalTeacher.isPresent()) {
      Stu stu = optionalStu.get();
      stu.setTeacher(optionalTeacher.get());
      stuRepository.save(stu);
    }


    return "redirect:/assignment/page?teacherId=" + teacherId;
  }


}
